package com.mindskip.xzs.service.impl;

import com.mindskip.xzs.domain.other.KeyValue;
import com.mindskip.xzs.domain.Question;
import com.mindskip.xzs.domain.TextContent;
import com.mindskip.xzs.domain.enums.QuestionStatusEnum;
import com.mindskip.xzs.domain.enums.QuestionTypeEnum;
import com.mindskip.xzs.domain.question.QuestionItemObject;
import com.mindskip.xzs.domain.question.QuestionObject;
import com.mindskip.xzs.repository.QuestionMapper;
import com.mindskip.xzs.service.QuestionService;
import com.mindskip.xzs.service.SubjectService;
import com.mindskip.xzs.service.TextContentService;
import com.mindskip.xzs.utility.DateTimeUtil;
import com.mindskip.xzs.utility.JsonUtil;
import com.mindskip.xzs.utility.ModelMapperSingle;
import com.mindskip.xzs.utility.ExamUtil;
import com.mindskip.xzs.viewmodel.admin.question.QuestionEditItemVM;
import com.mindskip.xzs.viewmodel.admin.question.QuestionEditRequestVM;
import com.mindskip.xzs.viewmodel.admin.question.QuestionPageRequestVM;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service // 表示这是一个服务类
public class QuestionServiceImpl extends BaseServiceImpl<Question> implements QuestionService {

    // 静态的 ModelMapper 实例，用于对象映射
    protected final static ModelMapper modelMapper = ModelMapperSingle.Instance();
    private final QuestionMapper questionMapper; // 题目数据库操作类
    private final TextContentService textContentService; // 文本内容服务类
    private final SubjectService subjectService; // 学科服务类

    @Autowired // 自动注入依赖
    public QuestionServiceImpl(QuestionMapper questionMapper, TextContentService textContentService, SubjectService subjectService) {
        super(questionMapper);
        this.textContentService = textContentService;
        this.questionMapper = questionMapper;
        this.subjectService = subjectService;
    }

    // 分页查询题目
    @Override
    public PageInfo<Question> page(QuestionPageRequestVM requestVM) {
        return PageHelper.startPage(requestVM.getPageIndex(), requestVM.getPageSize(), "id asc").doSelectPageInfo(() ->
                questionMapper.page(requestVM)
        );
    }

    // 插入完整题目
    @Override
    @Transactional // 表示这是一个事务性操作
    public Question insertFullQuestion(QuestionEditRequestVM model, Integer userId) {
        Date now = new Date(); // 获取当前时间

        // 插入题干、解析、选项等信息
        TextContent infoTextContent = new TextContent();
        infoTextContent.setCreateTime(now);
        setQuestionInfoFromVM(infoTextContent, model);
        textContentService.insertByFilter(infoTextContent); // 插入文本内容

        // 插入题目信息
        Question question = new Question();
        question.setSubjectId(model.getSubjectId());
        question.setCreateTime(now);
        question.setQuestionType(model.getQuestionType());
        question.setStatus(QuestionStatusEnum.OK.getCode());
        question.setInfoTextContentId(infoTextContent.getId());
        question.setCreateUser(userId);
        question.setDeleted(false);
        questionMapper.insertSelective(question); // 插入题目
        return question;
    }

    // 更新完整题目
    @Override
    @Transactional // 表示这是一个事务性操作
    public Question updateFullQuestion(QuestionEditRequestVM model) {
        Question question = questionMapper.selectByPrimaryKey(model.getId()); // 根据主键查询题目
        questionMapper.updateByPrimaryKeySelective(question); // 更新题目信息

        // 更新题干、解析、选项等信息
        TextContent infoTextContent = textContentService.selectById(question.getInfoTextContentId());
        setQuestionInfoFromVM(infoTextContent, model);
        textContentService.updateByIdFilter(infoTextContent); // 更新文本内容

        return question;
    }

    // 获取题目编辑请求视图模型
    @Override
    public QuestionEditRequestVM getQuestionEditRequestVM(Integer questionId) {
        Question question = questionMapper.selectByPrimaryKey(questionId); // 根据主键查询题目
        return getQuestionEditRequestVM(question); // 获取题目编辑请求视图模型
    }

    // 获取题目编辑请求视图模型
    @Override
    public QuestionEditRequestVM getQuestionEditRequestVM(Question question) {
        TextContent questionInfoTextContent = textContentService.selectById(question.getInfoTextContentId()); // 获取文本内容
        QuestionObject questionObject = JsonUtil.toJsonObject(questionInfoTextContent.getContent(), QuestionObject.class); // 将文本内容转换为题目对象
        QuestionEditRequestVM questionEditRequestVM = modelMapper.map(question, QuestionEditRequestVM.class); // 映射题目对象到视图模型
        questionEditRequestVM.setTitle(questionObject.getTitleContent()); // 设置标题

        // 根据题目类型设置答案
        QuestionTypeEnum questionTypeEnum = QuestionTypeEnum.fromCode(question.getQuestionType());
        switch (questionTypeEnum) {
            case SingleChoice:
            default:
                break;
        }

        // 映射题目项
        List<QuestionEditItemVM> editItems = questionObject.getQuestionItemObjects().stream().map(o -> {
            QuestionEditItemVM questionEditItemVM = modelMapper.map(o, QuestionEditItemVM.class);
            if (o.getScore() != null) {
                questionEditItemVM.setScore(ExamUtil.scoreToVM(o.getScore())); // 设置分数
            }
            return questionEditItemVM;
        }).collect(Collectors.toList());
        questionEditRequestVM.setItems(editItems); // 设置题目项
        return questionEditRequestVM;
    }

    // 从视图模型中设置题目信息
    public void setQuestionInfoFromVM(TextContent infoTextContent, QuestionEditRequestVM model) {
        List<QuestionItemObject> itemObjects = model.getItems().stream().map(i ->
                {
                    QuestionItemObject item = new QuestionItemObject();
                    item.setPrefix(i.getPrefix());
                    item.setContent(i.getContent());
                    item.setItemUuid(i.getItemUuid());
                    item.setScore(ExamUtil.scoreFromVM(i.getScore())); // 设置分数
                    return item;
                }
        ).collect(Collectors.toList());
        QuestionObject questionObject = new QuestionObject();
        questionObject.setQuestionItemObjects(itemObjects);
        questionObject.setTitleContent(model.getTitle()); // 设置标题
        infoTextContent.setContent(JsonUtil.toJsonStr(questionObject)); // 将题目对象转换为 JSON 字符串并设置为文本内容
    }

    // 查询所有题目数量
    @Override
    public Integer selectAllCount() {
        return questionMapper.selectAllCount();
    }

    // 查询每月题目数量
    @Override
    public List<Integer> selectMothCount() {
        Date startTime = DateTimeUtil.getMonthStartDay(); // 获取月初时间
        Date endTime = DateTimeUtil.getMonthEndDay(); // 获取月末时间
        List<String> mothStartToNowFormat = DateTimeUtil.MothStartToNowFormat(); // 获取从月初到现在的日期格式列表
        List<KeyValue> mouthCount = questionMapper.selectCountByDate(startTime, endTime); // 查询每个日期的题目数量
        return mothStartToNowFormat.stream().map(md -> {
            KeyValue keyValue = mouthCount.stream().filter(kv -> kv.getName().equals(md)).findAny().orElse(null);
            return null == keyValue ? 0 : keyValue.getValue(); // 如果没有找到对应日期的数量，则返回 0
        }).collect(Collectors.toList());
    }
}
